package leetcode.easy;

import java.util.Arrays;

/**
 * ClassName: $122_BestTimetoBuyandSellStockII
 * Description:
 * date: 2021-10-18 15:07
 *
 * @author liyifan
 */
public class $122_BestTimetoBuyandSellStockII {
    public int maxProfit(int[] prices) {
        if (minRange(prices))
            return 0;
        if (maxRange(prices))
            return prices[prices.length - 1] - prices[0];
        int currentMin = prices[0];
        int currentMax = currentMin;
        int res = 0;
        for (int i = 0;i < prices.length - 1;i++) {
            if (prices[i] <= currentMin && prices[i + 1] > prices[i]) {
                currentMin = prices[i];
                currentMax = currentMin;
                for (int j = i; j < prices.length;j++) {
                    if (j == prices.length - 1 && prices[j] > currentMax) {
                        currentMax = prices[j];
                        res += currentMax - currentMin;
                    } else if(prices[j] > currentMax && prices[j + 1] < prices[j]) {
                        currentMax = prices[j];
                        res += currentMax - currentMin;
                        currentMin = currentMax;
                        i = j - 1;
                        break;
                    }
                }
            }
        }
        return res;
    }

    public boolean minRange(int[] a){
        boolean flag = true;
        for (int i = 0;i < a.length - 1; i++) {
            if (a[i + 1] > a[i]){
                flag = false;
                break;
            }
        }
        return flag;
    }

    public boolean maxRange(int[] a){
        boolean flag = true;
        for (int i = 0;i < a.length - 1; i++) {
            if (a[i + 1] < a[i]){
                flag = false;
                break;
            }
        }
        return flag;
    }

    public int maxProfit2(int[] prices) {
        int n = prices.length;
        int[][] dp = new int[n][2];
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        for (int i = 1;i < n;i++) {
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
            dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
        }
        return dp[n - 1][0];
    }

    public int maxProfit3(int[] prices) {
        if (prices.length <= 1 || prices == null)
            return 0;
        int ans = 0;
        for (int i = 1;i < prices.length;i++) {
            ans += Math.max(0, prices[i] - prices[i - 1]);
        }
        return ans;
    }
}
